package com.example.demo.service.impl;

import com.example.demo.controller.resp.UserResp;
import com.example.demo.data.UserInfo;
import com.example.demo.data.dao.UserDao;
import com.example.demo.data.entity.UserDO;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    private Map<String, UserInfo> cache = new HashMap<>();

    private ReentrantLock lock = new ReentrantLock(true);

    @Override
    public UserResp check(String ipAddress, String code) {
        UserInfo info;
        try {
            lock.lock();
            info = cache.get(code);
            // 第一次进来，表示有了
            if (info == null) {
                UserInfo _info = new UserInfo();
                _info.setIpAddress(ipAddress);
                _info.setLastTime(System.currentTimeMillis());
                cache.put(code, _info);

                UserDO _user = userDao.findByIdentity(code);
                if (_user == null) {
                    userDao.save(buildUser(code));
                }
                return UserResp.active();
            };
            // 第二次进来，先看时间是否在三分钟以内 3*60*1000=180000
            long currTime = System.currentTimeMillis();
            // 3分钟以内触发过，返回false
            // 没触发过，返回true
            if (currTime - info.getLastTime() < 180000) {
                if (!ipAddress.equals(info.getIpAddress())) {
                    return UserResp.inactive();
                }
                return UserResp.active();
            } else {
                info.setLastTime(currTime);
                cache.put(code, info);
                return UserResp.active();
            }
        } finally {
            lock.unlock();
        }
    }

    private UserDO buildUser(String code) {
        UserDO user = new UserDO();
        user.setIdentity(code);
        user.setIsDelete(0);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return user;
    }
}
